class WebSocketClient {
    constructor() {
        this.ws = null;
        this.connected = false;
        this.retryCount = 0;
        this.maxRetries = 5;
        this.retryDelay = 3000;
        this.activeClient = null;
        this.statusLight = document.querySelector('.status-light');
        this.uploadProgressInterval = null;
        this.pausedFiles = new Set();
        this.init();
    }

    init() {
        this.updateStatusLight();
        this.connect();
        
        // 绑定客户端刷新按钮
        document.getElementById('refresh-clients')?.addEventListener('click', () => {
            this.retryCount = 0;
            if (!this.connected) {
                this.connect();
                setTimeout(() => {
                    this.updateStatusLight();
                    if (this.connected) {
                        this.sendMessage('get_clients_info');
                    }
                }, 500);
            } else {
                this.sendMessage('get_clients_info');
            }
        });
    }

    connect() {
        this.ws = new WebSocket('ws://127.0.0.1:8766');

        this.ws.onopen = () => {
            console.log('WebSocket connected');
            this.connected = true;
            this.retryCount = 0;
            this.updateStatusLight();
            this.sendMessage('get_clients_info');
        };

        this.ws.onmessage = (event) => this.handleMessage(event);
        this.ws.onerror = (error) => this.handleError(error);
        this.ws.onclose = () => this.handleClose();
    }

    handleMessage(event) {
        try {
            const data = JSON.parse(event.data);
            console.log('Received:', data);

            if (data.type === 'clients_info') {
                this.updateClientList(data.clients);
            }
            if (data.type === 'file_tree') {
                this.updateFileTree(data.client_id, data.files);
            }
            if (data.type === 'upload_progress') {
                this.updateUploadProgress({
                    name: data.file_name,
                    hash: data.file_hash,
                    progress: data.progress
                });
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    }

    updateClientList(clients) {
        const clientList = document.getElementById('client-list');
        const listContainer = document.createElement('div');
        listContainer.id = 'client-list-container';

        const connectedClientIds = new Set(clients.map(c => c.client_id));

        if (this.activeClient && !connectedClientIds.has(this.activeClient)) {
            this.activeClient = null;
            document.getElementById('file-tree-container').innerHTML = '';
        }

        const oldContainer = document.getElementById('client-list-container');
        if (oldContainer) {
            oldContainer.remove();
        }

        clients.forEach(client => {
            const clientDiv = document.createElement('div');
            clientDiv.className = 'client-item';
            clientDiv.id = `client-${client.client_id}`;

            if (this.activeClient === client.client_id) {
                clientDiv.classList.add('active');
            }

            const icon = document.createElement('i');
            icon.className = 'fa-solid fa-desktop';

            const label = document.createElement('span');
            label.textContent = `Client ${client.client_id}`;

            clientDiv.appendChild(icon);
            clientDiv.appendChild(label);

            clientDiv.addEventListener('click', () => {
                this.selectClient(client.client_id);
            });

            listContainer.appendChild(clientDiv);
        });

        clientList.appendChild(listContainer);
    }

    selectClient(clientId) {
        if (this.activeClient === clientId) {
            const activeClientDiv = document.querySelector(`#client-${clientId}`);
            if (activeClientDiv) {
                activeClientDiv.classList.remove('active');
            }
            this.activeClient = null;
            document.getElementById('file-tree-container').innerHTML = '';
            return;
        }

        const prevActive = document.querySelector('.client-item.active');
        if (prevActive) {
            prevActive.classList.remove('active');
        }
        const newActive = document.querySelector(`#client-${clientId}`);
        if (newActive) {
            newActive.classList.add('active');
        }

        this.activeClient = clientId;
        this.sendMessage('get_file_tree', { client_id: clientId });
    }

    updateFileTree(clientId, files) {
        const fileTreeContainer = document.getElementById('file-tree-container');
        fileTreeContainer.innerHTML = '';

        const renderTree = (node, path = '') => {
            const ul = document.createElement('ul');
            ul.style.listStyle = 'none';
            ul.style.paddingLeft = '20px';

            const sortedChildren = node.children.slice().sort((a, b) => {
                if (a.type === 'directory' && b.type !== 'directory') return -1;
                if (a.type !== 'directory' && b.type === 'directory') return 1;
                return a.name.localeCompare(b.name);
            });

            sortedChildren.forEach(item => {
                const li = document.createElement('li');
                const isFolder = item.type === 'directory';

                const icon = document.createElement('i');
                icon.className = isFolder ? 'fa-solid fa-folder' : 'fa-solid fa-file';
                icon.style.marginRight = '8px';
                icon.style.color = isFolder ? '#ffd43b' : '#74c0fc';

                const name = document.createElement('span');
                name.textContent = item.name;

                const size = document.createElement('span');
                size.textContent = item.type === 'file' ? ` (${item.size_formatted})` : '';
                size.style.color = '#666';
                size.style.marginLeft = '8px';

                const container = document.createElement('div');
                container.className = 'file-item';
                if (!isFolder && item.exists) {
                    container.classList.add('file-exists');
                }

                const progressBar = document.createElement('div');
                progressBar.className = 'progress-bar';
                container.appendChild(progressBar);

                const content = document.createElement('div');
                content.className = 'content';
                content.appendChild(icon);
                content.appendChild(name);
                content.appendChild(size);
                container.appendChild(content);

                li.appendChild(container);

                if (isFolder) {
                    li.style.cursor = 'pointer';
                    container.addEventListener('click', (e) => {
                        e.stopPropagation();
                        const childUl = li.querySelector('ul');
                        if (childUl) {
                            childUl.style.display = childUl.style.display === 'none' ? 'block' : 'none';
                            icon.className = childUl.style.display === 'none' ?
                                'fa-solid fa-folder' : 'fa-solid fa-folder-open';
                        }
                    });

                    if (item.children && item.children.length > 0) {
                        const childUl = renderTree(item, path ? `${path}/${item.name}` : item.name);
                        li.appendChild(childUl);
                    }
                } else {
                    container.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.sendMessage('file_click', {
                            client_id: clientId,
                            filename: path ? `${path}/${item.name}` : item.name
                        });
                        this.startUploadProgressCheck(clientId, path ? `${path}/${item.name}` : item.name, progressBar);
                    });
                }

                ul.appendChild(li);
            });

            return ul;
        };

        const fileTree = renderTree(files);
        fileTreeContainer.appendChild(fileTree);
    }
startUploadProgressCheck(clientId, filepath, progressBar) {
    console.log('Starting progress check for:', filepath);
    
    // 如果已经有定时器在运行，先停止
    this.stopUploadProgressCheck();
    
    // 设置新的定时器
    this.uploadProgressInterval = setInterval(() => {
        try {
            if (!this.connected) {
                console.log('WebSocket not connected, stopping progress check');
                this.stopUploadProgressCheck();
                return;
            }
            
            const success = this.sendMessage('file_upload_progress', {
                client_id: clientId,
                file_path: filepath
            });
            
            if (!success) {
                console.log('Failed to send progress request, stopping check');
                this.stopUploadProgressCheck();
            }
        } catch (error) {
            console.error('Error sending progress request:', error);
            this.stopUploadProgressCheck();
        }
    }, 500);

        // 更新进度条回调
        this.updateFileProgressBar = (progress) => {
            try {
                console.log('Received progress update:', progress);
                const progressPercent = Math.round(progress);
                if (progressBar) {
                    progressBar.style.width = `${progressPercent}%`;
                    const progressText = progressBar.parentElement.querySelector('.progress-text');
                    if (progressText) {
                        progressText.textContent = `${progressPercent}%`;
                    }
                }
                if (progressPercent >= 100) {
                    console.log('Upload completed for:', filepath);
                    this.stopUploadProgressCheck();
                }
            } catch (error) {
                console.error('Error updating progress bar:', error);
            }
        };
        
        // 立即发送第一次请求
        console.log('Sending initial progress request');
        this.sendMessage('file_upload_progress', {
            client_id: clientId,
            file_path: filepath
        });
    }

    stopUploadProgressCheck() {
        if (this.uploadProgressInterval) {
            console.log('Stopping progress check');
            clearInterval(this.uploadProgressInterval);
            this.uploadProgressInterval = null;
            this.updateFileProgressBar = null;
        }
    }

    createProgressBox() {
        const box = document.createElement('div');
        box.id = 'upload-progress-box';
        box.className = 'upload-progress-box';
        
        // 标题栏
        const header = document.createElement('div');
        header.className = 'progress-box-header';
        header.innerHTML = `
            <span>文件上传进度</span>
        `;

        // 内容区域
        const content = document.createElement('div');
        content.className = 'progress-box-content';
        
        // 进度列表容器
        const progressList = document.createElement('div');
        progressList.id = 'progress-list';
        progressList.className = 'progress-list';
        
        content.appendChild(progressList);
        box.appendChild(header);
        box.appendChild(content);
        
        document.body.appendChild(box);
        return box;
    }

    updateUploadProgress(fileInfo) {
        try {
            let box = document.getElementById('upload-progress-box');
            if (!box) {
                box = this.createProgressBox();
                document.body.appendChild(box);
            }

            const progressList = box.querySelector('#progress-list');
            
            // 查找或创建进度项
            let item = progressList.querySelector(`[data-file="${fileInfo.name}"]`);
            if (!item) {
                item = document.createElement('div');
                item.className = 'progress-item';
                item.setAttribute('data-file', fileInfo.name);
                item.innerHTML = `
                    <div class="filename">${fileInfo.name}</div>
                    <div class="progress-bar">
                        <div class="progress-bar-inner"></div>
                    </div>
                    <div class="progress-text">0%</div>
                    <button class="action-btn ${fileInfo.progress < 100 ? 'pause-btn' : 'delete-btn'}">
                        <i class="fa-solid ${fileInfo.progress < 100 ? 'fa-pause' : 'fa-xmark'}"></i>
                    </button>
                `;

                // 添加按钮点击事件
                const actionBtn = item.querySelector('.action-btn');
                if (actionBtn) {
                    actionBtn.addEventListener('click', () => {
                        if (actionBtn.classList.contains('pause-btn')) {
                            if (this.pausedFiles.has(fileInfo.name)) {
                                // 继续上传
                                this.sendMessage('resume_upload', {
                                    client_id: this.activeClient,
                                    file_hash: fileInfo.hash
                                });
                                this.pausedFiles.delete(fileInfo.name);
                                actionBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
                                actionBtn.title = '暂停上传';
                                
                                // 恢复进度查询
                                console.log('Resuming upload for:', fileInfo.name);
                                if (!this.connected) {
                                    console.error('WebSocket not connected');
                                    return;
                                }
                                
                                const fileItem = actionBtn.closest('.progress-item');
                                if (fileItem) {
                                    // 确保停止之前的定时器
                                    this.stopUploadProgressCheck();
                                    
                                    const progressBar = fileItem.querySelector('.progress-bar');
                                    if (!progressBar) {
                                        console.error('Progress bar not found');
                                        return;
                                    }
                                    
                                    try {
                                        // 启动定时查询
                                        this.startUploadProgressCheck(
                                            this.activeClient,
                                            fileInfo.name,
                                            progressBar
                                        );
                                    } catch (error) {
                                        console.error('Error resuming upload:', error);
                                    }
                                }
                            } else {
                                // 暂停上传
                                this.sendMessage('pause_upload', {
                                    client_id: this.activeClient,
                                    file_hash: fileInfo.hash
                                });
                                this.pausedFiles.add(fileInfo.name);
                                actionBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
                                actionBtn.title = '继续上传';
                                this.stopUploadProgressCheck();
                            }
                        } else if (actionBtn.classList.contains('delete-btn')) {
                            // 删除单个文件项目
                            item.remove();
                        }
                    });
                }
                progressList.appendChild(item);
            }

            // 更新进度
            const progressPercent = Math.round(fileInfo.progress);
            const progressBar = item.querySelector('.progress-bar-inner');
            const progressText = item.querySelector('.progress-text');
            
            progressBar.style.width = `${progressPercent}%`;
            progressText.textContent = `${progressPercent}%`;

            // 上传完成处理
            if (fileInfo.progress >= 100) {
                this.stopUploadProgressCheck();
                // 保留完成的上传记录
                item.classList.add('completed');
                const progressText = item.querySelector('.progress-text');
                if (progressText) {
                    progressText.textContent = '上传完成';
                }
                
                // 更新操作按钮
                const actionBtn = item.querySelector('.action-btn');
                if (actionBtn) {
                    actionBtn.classList.remove('pause-btn');
                    actionBtn.classList.add('delete-btn');
                    actionBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
                    actionBtn.title = '删除此文件';
                }
            }
        } catch (error) {
            console.error('Error updating upload progress:', error);
        }
    }

    sendMessage(type, data = {}) {
        try {
            if (!this.connected || !this.ws || this.ws.readyState !== WebSocket.OPEN) {
                console.error('Cannot send message - WebSocket not connected');
                return false;
            }
            const message = { type, ...data };
            this.ws.send(JSON.stringify(message));
            return true;
        } catch (error) {
            console.error('Error sending WebSocket message:', error);
            return false;
        }
    }

    updateStatusLight() {
        this.statusLight.classList.remove('connected', 'disconnected', 'connecting');
        if (this.connected) {
            this.statusLight.classList.add('connected');
        } else if (this.retryCount > 0 && this.retryCount < this.maxRetries) {
            this.statusLight.classList.add('connecting');
        } else {
            this.statusLight.classList.add('disconnected');
        }
    }

    handleError(error) {
        console.error('WebSocket error:', error);
        this.updateStatusLight();
    }

    handleClose() {
        console.log('WebSocket disconnected');
        this.connected = false;
        this.updateStatusLight();
        if (this.retryCount < this.maxRetries) {
            this.retryCount++;
            console.log(`Reconnecting in ${this.retryDelay / 1000} seconds...`);
            setTimeout(() => {
                this.connect();
                this.updateStatusLight();
            }, this.retryDelay);
        } else {
            this.updateStatusLight();
        }
    }
}

// 初始化 WebSocket 客户端
const wsClient = new WebSocketClient();